package cn.com.cdb.ldms.modules.system.components;

import org.springframework.web.bind.annotation.*;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class PathUtils {

    private static final Class<?>[] MAPPING_ANNOTATIONS = {
            RequestMapping.class,
            GetMapping.class,
            PostMapping.class,
            PutMapping.class,
            DeleteMapping.class,
            PatchMapping.class
    };

    public static String[] getClassPaths(Class<?> clazz) {
        return getPathsFromAnnotation(clazz.getAnnotations());
    }

    public static String[] getMethodPaths(Method method) {
        return getPathsFromAnnotation(method.getAnnotations());
    }

    private static String[] getPathsFromAnnotation(Annotation[] annotations) {
        for (Annotation annotation : annotations) {
            for (Class<?> mappingAnnotation : MAPPING_ANNOTATIONS) {
                if (mappingAnnotation.isInstance(annotation)) {
                    try {
                        // 统一调用value()方法获取路径
                        return (String[]) mappingAnnotation
                                .getMethod("value")
                                .invoke(annotation);
                    } catch (Exception e) {
                        return new String[]{""};
                    }
                }
            }
        }
        return new String[]{""};
    }

    public static RequestMethod getMethodType(Annotation annotation) {
        if (annotation instanceof GetMapping) return RequestMethod.GET;
        if (annotation instanceof PostMapping) return RequestMethod.POST;
        if (annotation instanceof PutMapping) return RequestMethod.PUT;
        if (annotation instanceof DeleteMapping) return RequestMethod.DELETE;
        if (annotation instanceof PatchMapping) return RequestMethod.PATCH;
        if (annotation instanceof RequestMapping) {
            RequestMapping mapping = (RequestMapping) annotation;
            return mapping.method().length > 0 ? mapping.method()[0] : RequestMethod.GET;
        }
        return null;
    }
}